package com.ezjie.ielts.service;

import java.util.List;

import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;

import com.alibaba.fastjson.JSON;
import com.ezjie.ielts.R;
import com.ezjie.ielts.core.http.HttpRequestAbstractCallBack;
import com.ezjie.ielts.db.WordDao;
import com.ezjie.ielts.db.WordInstanceDao;
import com.ezjie.ielts.db.WordMeaningDao;
import com.ezjie.ielts.db.WordQuestionDao;
import com.ezjie.ielts.model.Eword;
import com.ezjie.ielts.model.EwordInstance;
import com.ezjie.ielts.model.EwordMeaning;
import com.ezjie.ielts.model.EwordQuestion;
import com.ezjie.ielts.model.UpdateWord;
import com.ezjie.ielts.model.UpdateWordInstance;
import com.ezjie.ielts.model.UpdateWordMeaning;
import com.ezjie.ielts.model.UpdateWordQuestion;
import com.ezjie.ielts.model.WordNewData;
import com.ezjie.ielts.model.WordNewResponse;
import com.ezjie.ielts.task.WordNewTask;
import com.ezjie.ielts.util.AppUtil;
import com.ezjie.ielts.util.LogUtils;
import com.ezjie.ielts.util.WordHomeDataUtil;
import com.lidroid.xutils.exception.HttpException;

/**
 * 单词更新service
 * 
 * @author renyangyang
 *
 */
public class DownloadWordService extends Service {
	private static final int MSG_REFRESH = 111;
	private WordDao wordDao;
	private WordInstanceDao wordInstanceDao;
	private WordMeaningDao wordMeaningDao;
	private WordQuestionDao wordQuestionDao;

	private WordNewTask wordTask;

	@Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public void onCreate() {
		super.onCreate();
		LogUtils.d("onCreate() executed");
		wordTask = new WordNewTask(getApplicationContext());
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		LogUtils.d("onStartCommand() executed ");
		if (wordDao == null) {
			wordDao = new WordDao(this);
		}
		if (wordInstanceDao == null) {
			wordInstanceDao = new WordInstanceDao(this);
		}
		if (wordMeaningDao == null) {
			wordMeaningDao = new WordMeaningDao(this);
		}
		if (wordQuestionDao == null) {
			wordQuestionDao = new WordQuestionDao(this);
		}

		boolean request = intent.getBooleanExtra("request", true);
		if (request) {
			getUpdateData();
		}

		return super.onStartCommand(intent, flags, startId);
	}

	private void getUpdateData() {
		wordTask.getWordNew(new HttpRequestAbstractCallBack(this,false) {
			@Override
			public void onStartCallBack() {
				super.onStartCallBack();
				sendBroadcast(ConfigUtil.DOWNLOADING);
			}

			@Override
			public void onSuccessCallBack(String result) {
				super.onSuccessCallBack(result);
				LogUtils.d(result);
				// 放到线程中 解析
				startDownload(result);
			}

			@Override
			public void onFailureCallBack(HttpException error, String msg) {
				super.onFailureCallBack(error, msg);
				LogUtils.e(msg);
				sendBroadcast(ConfigUtil.ERROR);
				AppUtil.showToast(getApplicationContext(), R.string.load_net_data_failure);
			}
		});
	}

	Handler handler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			if (msg.what == MSG_REFRESH) {
				sendBroadcast(ConfigUtil.DOWNLOADING);
				handler.sendEmptyMessageDelayed(MSG_REFRESH, 200);
			}
		}

	};

	private void startDownload(final String response) {
		new Thread() {
			public void run() {
				try {
					WordNewResponse wordNewResponse = JSON.parseObject(response, WordNewResponse.class);
					if (wordNewResponse != null && 200 == wordNewResponse.getStatus_code()) {
						WordNewData data = wordNewResponse.getData();
						if (data != null) {
							sendBroadcast(ConfigUtil.DOWNLOADING);
							handler.sendEmptyMessageDelayed(MSG_REFRESH, 200);

							try {
								UpdateWord word = data.getWord();
								if (word != null) {
									List<Eword> create = word.getCreate();
									List<Eword> update = word.getUpdate();
									if (create != null && create.size() > 0) {
										wordDao.updateList(create);
									} else {
										LogUtils.d("没有插入的单词");
									}
									if (update != null && update.size() > 0) {
										wordDao.updateList(update);
									} else {
										LogUtils.d("没有更新的单词");
									}
								} else {
									LogUtils.d("没有更新的单词");
								}
								UpdateWordInstance instance = data.getInstance();
								if (instance != null) {
									List<EwordInstance> create = instance.getCreate();
									List<EwordInstance> update = instance.getUpdate();
									if (create != null && create.size() > 0) {
										wordInstanceDao.updateList(create);
									} else {
										LogUtils.d("没有插入的例句");
									}
									if (update != null && update.size() > 0) {
										wordInstanceDao.updateList(update);
									} else {
										LogUtils.d("没有更新的例句");
									}
								} else {
									LogUtils.d("没有更新的例句");
								}
								UpdateWordMeaning meaning = data.getMeaning();
								if (meaning != null) {
									List<EwordMeaning> create = meaning.getCreate();
									List<EwordMeaning> update = meaning.getUpdate();
									if (create != null && create.size() > 0) {
										wordMeaningDao.updateList(create);
									} else {
										LogUtils.d("没有插入的翻译");
									}
									if (update != null && update.size() > 0) {
										wordMeaningDao.updateList(update);
									} else {
										LogUtils.d("没有更新的翻译");
									}
								} else {
									LogUtils.d("没有更新的翻译");
								}
								UpdateWordQuestion question = data.getQuestion();
								if (question != null) {
									List<EwordQuestion> create = question.getCreate();
									List<EwordQuestion> update = question.getUpdate();
									if (create != null && create.size() > 0) {
										wordQuestionDao.updateList(create);
									} else {
										LogUtils.d("没有插入的题目");
									}
									if (update != null && update.size() > 0) {
										wordQuestionDao.updateList(update);
									} else {
										LogUtils.d("没有更新的题目");
									}
								} else {
									LogUtils.d("没有更新的题目");
								}

								Thread.sleep(1500);
								// 保存 更新的时间 和 把是否有更新置为false
								String update_time = data.getUpdate_time();
								if (update_time == null) {
									update_time = "";
								}
								WordHomeDataUtil.putWordUpdateTime(DownloadWordService.this, update_time);
								WordHomeDataUtil.putWordHaveUpdate(DownloadWordService.this, false);
								sendBroadcast(ConfigUtil.DOWNLOADED);
								handler.removeMessages(MSG_REFRESH);
							} catch (Exception e) {
								sendBroadcast(ConfigUtil.ERROR);
								handler.removeMessages(MSG_REFRESH);
							}
						} else {
							sendBroadcast(ConfigUtil.DOWNLOADED);
						}

					} else {
						sendBroadcast(ConfigUtil.ERROR);
					}
				} catch (Exception e) {
					LogUtils.d("json数据异常");
					LogUtils.exception(e);
					sendBroadcast(ConfigUtil.ERROR);
				}
			}
		}.start();
	}

	private void sendBroadcast(int status) {
		Intent intent = new Intent(ConfigUtil.WORD_ACTION_DOWNLOADING);
		intent.putExtra("status", status);
		sendBroadcast(intent);
	}
}
